package com.tiger.project.service.impl;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.tiger.common.core.redis.RedisCache;
import com.tiger.common.utils.Code;
import com.tiger.common.utils.DateUtils;
import com.tiger.common.utils.StringUtils;
import com.tiger.project.domain.*;
import com.tiger.project.mapper.CommonDecisionMapper;
import com.tiger.project.mapper.ContractEnclosureMapper;
import com.tiger.project.mapper.ContractMapper;
import com.tiger.project.mapper.ProjectAcceptanceMapper;
import com.tiger.project.service.IContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 【合同申请】Service业务层处理
 *
 * @author standard
 * @date 2022-09-19
 */
@Service
public class ContractServiceImpl implements IContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ContractEnclosureMapper contractEnclosureMapper;
    @Autowired
    private CommonDecisionMapper decisionMapper;
    @Autowired
    private ProjectAcceptanceMapper projectAcceptanceMapper;

    /**
     * 查询【合同申请】
     *
     * @param id 【合同申请】主键
     * @return 【合同申请】
     */
    @Override
    public Contract selectContractById(Long id) {
        Contract contract = contractMapper.selectContractById(id);
        //附件
        ContractEnclosure enclosure = new ContractEnclosure();
        enclosure.setContractApplyId(id);
        List<ContractEnclosure> contractEnclosureList = contractEnclosureMapper.selectContractEnclosureList(enclosure);
        if (contractEnclosureList !=null && contractEnclosureList.size() > 0){
            contract.getEnclosureList().addAll(contractEnclosureList);
        }

        //决策依据
        String decisionBasisIds = contract.getDecisionBasisIds();
        if (StringUtils.isNotEmpty(decisionBasisIds)){
            List<String> ids = Arrays.asList(decisionBasisIds.split(","));
            for (String i : ids){
                CommonDecision decision = decisionMapper.selectCommonDecisionById(Long.valueOf(i));
                contract.getCommonDecisionList().add(decision);
            }
        }
        return contract;
    }

    /**
     * 查询【合同申请】列表
     *
     * @param contract 【合同申请】
     * @return 【合同申请】
     */
    @Override
    public List<Contract> selectContractList(Contract contract) {
        return contractMapper.selectContractList(contract);
    }

    /**
     * 新增【合同申请】
     *
     * @param contract 【合同申请】
     * @return 结果
     */
    @Override
    public int insertContract(Contract contract) {
        int code = redisCache.getCacheObjectCode(LocalDate.now().format(Code.fmt) + "xmht");
        addCode(code);
        contract.setContractNo(String.format("%s%s%04d", "XMHT",LocalDate.now().format(Code.fmt), code));
        contract.setCreatedAt(DateUtils.getNowDate());
        contract.setIsDeleted(0L);
        contract.setStatus(1L);//未提交
        int i = contractMapper.insertContract(contract);
        change(contract);
        return i;
    }

    /**
     * 修改【合同申请】
     *
     * @param contract 【合同申请】
     * @return 结果
     */
    @Override
    public int updateContract(Contract contract) {
        change(contract);
        contract.setUpdatedAt(DateUtils.getNowDate());
        return contractMapper.updateContract(contract);
    }

    @Override
    public int callBack(Long id,Long status,String oaFile) {
        Contract contract = contractMapper.selectContractById(id);
        contract.setStatus(status);
        contract.setOaFile(oaFile);
        contract.setUpdatedAt(DateUtils.getNowDate());
        if (contract.getStatus() == 3L){
            ProjectAcceptance projectAcceptance = new ProjectAcceptance();
            projectAcceptance.setContractId(contract.getId());
            projectAcceptance.setName(contract.getName());
            projectAcceptance.setContractNo(contract.getContractNo());
            projectAcceptance.setTotalAmount(contract.getTotalAmount());
            projectAcceptance.setStatus(1L); //默认待验收
            projectAcceptance.setIsDeleted(0L);
            projectAcceptance.setCompanyId(contract.getCompanyId());
            projectAcceptanceMapper.insertProjectAcceptance(projectAcceptance);
        }
        return contractMapper.updateContract(contract);
    }

    /**
     * 批量删除【合同申请】
     *
     * @param ids 需要删除的【合同申请】主键
     * @return 结果
     */
    @Override
    public int deleteContractByIds(Long[] ids) {
        return contractMapper.deleteContractByIds(ids);
    }

    /**
     * 删除【合同申请】信息
     *
     * @param id 【合同申请】主键
     * @return 结果
     */
    @Override
    public int deleteContractById(Long id) {
        return contractMapper.deleteContractById(id);
    }

    /**
     * 生成编码
     */
    private synchronized void addCode(int code) {
        redisCache.setCacheObject(LocalDate.now().format(Code.fmt) + "xmht", code + 1);
    }


    private void change(Contract contract){
        //附件
        contractEnclosureMapper.deleteContractEnclosureByContractId(contract.getId());
        if (StringUtils.isNotEmpty(contract.getEnclosureList())){
            contract.getEnclosureList().forEach(item ->{
                item.setCreatedAt(DateUtils.getNowDate());
                item.setState("1");//上传成功
                item.setContractApplyId(contract.getId());
                contractEnclosureMapper.insertContractEnclosure(item);
            });
        }
    }


}
